from Products.KnowledgeEngine.KERL.Tokens.Token import Token
from Products.KnowledgeEngine.KERL.Operators import *
from Products.KnowledgeEngine.Services.MySQLFiveAssessmentStorageService.MySQLFiveAssessmentStorageService import qstr, qlist
from DateTime import DateTime
   
import types

   
class ComponentToken(Token):
                
    _implements = Token._implements + ("ComponentToken",)
                
    operators = Token.operators.copy()
    
    operators.update( {
        'selected'   : SelectedOperator,
        'unselected' : UnselectedOperator,
        'contains'   : Contains,
        'doesntcontain': DoesntContain,
        'equals'     : Equals,
        'notequals'  : NotEquals,
        '='          : Equals,
        '!='         : NotEquals,
        '>'          : GreaterThan,
        'greaterthan': GreaterThan,                
        '<'          : LessThan,
        'lessthan'   : LessThan,
        
        'greaterthanequal': GreaterThanEqual,
        '>='              : GreaterThanEqual,
        'lessthanequal'   : LessThanEqual,
        '<='              : LessThanEqual,
        
        'inrange'         : InRange,
        'notinrange'      : NotInRange,
        
        'firstattempt'    : FirstAttempt,
        'empty'           : Empty,
        'notempty'        : NotEmpty,
    })
                
    def __init__(self, object, namespace):
        """ Token wraps this object """
        
        if not object:
            raise "Creating ComponentToken without a component"
        
        self.object    = object
        self.namespace = namespace                        
                
    def toEnglish(self):
        """ Compiles this token into english """
        
        return "Component: %s (%s)" % (self.object.getIdentity(), self.object.title_or_id())

    def toSQL( self ):
        
        return """ 
assessmentIdentity IN (
    SELECT assessmentIdentity 
    FROM latestAnswers 
    WHERE componentIdentity = %s 
    AND   value             %%s
)
        """ % ( qstr( self.object.getIdentity() )) 
                

    def toJavascript( self ):
        
        return "document.getElementById('%s').value" % self.getObject().getIdentity()

    # -----------------------------------------------------------------------------

    def equals(self, other, assessment):
        """ Overload the Equals operator for Components """
                
        component         = self.getObject()
        componentIdentity = component.getIdentity()
        
        myValue    = assessment.getComponentByIdentityValue( componentIdentity )
        otherValue = other.getObject()
        
        #print "ComponentToken::equals: %s == %s" % ( `myValue`, `otherValue`  )
        
        return myValue == otherValue
        
    # -----------------------------------------------------------------------------
        
    def contains(self, other, assessment):            
        """ Overload the contains operator for Components """
        
        component         = self.getObject()
        componentIdentity = component.getIdentity()
        
        myValue    = assessment.getComponentByIdentityValue( componentIdentity )
        otherValue = other.getObject()
        
        #print "ComponentToken::contains: %s ?? %s" % ( `myValue`, `otherValue`  )
        
        return otherValue in myValue
            
    # -----------------------------------------------------------------------------
    
    def getValue(self, assessment):
        """ Returns this tokens component value """
        
        component         = self.getObject()
        componentIdentity = component.getIdentity()
        
        myValue    = assessment.getComponentByIdentityValue( componentIdentity )
        
        return myValue
        
    
    # -----------------------------------------------------------------------------
            
    def findOperator(self, operator):
        """ Finds the relevant operator """
         
        object = self.getObject()
        if hasattr(object, 'findKERLOperator'):
            myoperator = object.findKERLOperator( operator )
            if myoperator:
                return myoperator
            
        # No component specific operator found, try basic operators
        return Token.findOperator( self, operator )
            
        #try:
            #return self.operators[ operator ]
        #except KeyError:
            #raise "Cannot find operator %s" % operator            
            
        
    def toKERL(self):
        return "'%s'" % self.getObject().getIdentity()
    
#class OptionComponentToken( ComponentToken ):
        
        #_implements = ComponentToken._implements + ("OptionComponentToken",)
        
        #operators = dict(ComponentToken.operators)
        #operators['selected'] = SelectedOperator
        
        #def toJavascript( self ):
            #return "document.getElementById('%s').value" % self.getObject().getIdentity()